<template>
    <el-dialog v-model="isOpen" title="关联度分析" width="1200" :border="true" align-center>
        <div class="result_show">
            <div class="left">

                <div class="eChartContainer flex-row justify-center align-center">
                    <div ref="chartRef" class="chart" />
                </div>

                <div class="correlation-stats mt-4">
                    <h4 class="text-lg font-semibold mb-2">分析信息</h4>
                    <el-descriptions column="2" border>
                        <el-descriptions-item label="分析变量">{{ featureNames.join("、") }}</el-descriptions-item>
                        <el-descriptions-item label="样本数量">{{ sampleCount }}</el-descriptions-item>
                        <el-descriptions-item label="变量数量">{{ variableCount }}</el-descriptions-item>
                        <el-descriptions-item label="计算时间">{{ computeTime }}ms</el-descriptions-item>
                    </el-descriptions>
                </div>
            </div>

            <div class="right">
                <h4>相关系数详情</h4>
                <el-table :data="formattedCorrelations" border max-height="100%">
                    <el-table-column prop="variableX" label="变量X" />
                    <el-table-column prop="variableY" label="变量Y" />
                    <el-table-column prop="correlation" label="相关系数">
                        <template #default="scope">
                            <span :class="getCorrelationClass(scope.row.correlation)">
                                {{ scope.row.correlation.toFixed(2) }}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column prop="interpretation" label="相关性解读" />
                </el-table>
            </div>
        </div>

        <template #footer>
            <el-button type="primary" @click="isOpen = false">关闭</el-button>
        </template>
    </el-dialog>
</template>

<script setup>
import { computed, nextTick, onUnmounted, ref, watch } from "vue"
import * as echarts                                    from "echarts"

let isOpen = defineModel()
let props  = defineProps([ "result", "originalData" ])

const chartRef    = ref(null)
let chartInstance = ref(null)

// 提取特征名称（分析的变量）
const featureNames = computed(() => {
    if(!props.originalData?.listColumn){
        return []
    }
    return props.originalData.listColumn.map(item => item.key)
})

// 样本数量（水果种类数量）
const sampleCount = computed(() => {
    return props.originalData?.listAll?.length || 0
})

// 变量数量和计算时间
const variableNames = computed(() => props.result?.variableNames || [])
const variableCount = computed(() => variableNames.value.length)
const computeTime   = computed(() => props.result?.computeTime || 0)

// 格式化相关系数数据用于表格展示
const formattedCorrelations = computed(() => {
    if(!props.result?.heatmapData){
        return []
    }

    return props.result.heatmapData
                .filter(item => item.x <= item.y) // 只显示上三角（避免重复）
                .map(item => ({
                    variableX     : item.x,
                    variableY     : item.y,
                    correlation   : item.value,
                    interpretation: getCorrelationInterpretation(item.value),
                }))
})

// 根据相关系数值返回解读文本
function getCorrelationInterpretation(value){
    const absValue = Math.abs(value)
    if(absValue >= 0.8){
        return "强相关"
    }
    if(absValue >= 0.5){
        return "中等相关"
    }
    if(absValue >= 0.3){
        return "弱相关"
    }
    return "几乎无相关"
}

// 根据相关系数值返回样式类名
function getCorrelationClass(value){
    const absValue = value
    if(absValue >= 0.8){
        return "strong-correlation"
    }
    if(absValue >= 0.5){
        return "medium-correlation"
    }
    if(absValue >= 0.3){
        return "weak-correlation"
    }
    return "no-correlation"
}

watch(isOpen, (val) => {
    if(val){
        initChart()
    }
    else{
        cleanupChart()
    }
})

// 清理图表资源
function cleanupChart(){
    if(chartInstance.value){
        chartInstance.value.dispose()
        chartInstance.value = null
    }
    window.removeEventListener("resize", handleResize)
}

// 处理窗口大小变化
function handleResize(){
    if(chartInstance.value){
        chartInstance.value.resize()
    }
}

function initChart(){
    nextTick(() => {
        if(!chartRef.value || !props.result){
            return
        }

        if(!chartInstance.value){
            chartInstance.value = echarts.init(chartRef.value)
        }

        const { heatmapData, variableNames } = props.result

        // 准备热力图数据
        const processedData = heatmapData.map(item => ({
            x    : item.x,
            y    : item.y,
            value: item.value,
            // 保存原始值用于tooltip
            originalValue: item.value,
        }))

        const option = {
            title    : [
                {
                    text     : `变量相关性热力图`,
                    left     : "center",
                    top      : 10,
                    textStyle: { fontSize: 16, color: "#303133" },
                },
                {
                    text     : `分析维度: ${ featureNames.value.join("、") }`,
                    left     : "center",
                    top      : 40,
                    textStyle: { fontSize: 14, color: "#606266" },
                },
            ],
            tooltip  : {
                trigger        : "item",
                formatter      : function(params){
                    const val = params.data.originalValue
                    return `${ params.data.x } 与 ${ params.data.y } 的相关系数:
                            ${ val.toFixed(4) }<br>
                            相关性: ${ getCorrelationInterpretation(val) }`
                },
                backgroundColor: "rgba(255, 255, 255, 0.9)",
                borderColor    : "#ddd",
                borderWidth    : 1,
                textStyle      : { color: "#333" },
            },
            grid     : {
                left        : "10%",
                right       : "15%",
                bottom      : "20%",
                top         : "15%",
                containLabel: true,
            },
            xAxis    : {
                type        : "category",
                data        : variableNames,
                name        : "水果名称",
                nameLocation: "middle",
                nameGap     : 30,
                axisLabel   : {
                    interval: 0,
                    rotate  : 45,
                    fontSize: 12,
                },
            },
            yAxis    : {
                type        : "category",
                data        : variableNames,
                name        : "水果名称",
                nameLocation: "middle",
                nameGap     : 40,
                axisLabel   : {
                    fontSize: 12,
                },
            },
            visualMap: {
                type      : "continuous",
                min       : -1,
                max       : 1,
                calculable: true,
                orient    : "horizontal",
                left      : "center",
                bottom    : 20,
                text      : [ "正相关强", "负相关强" ],
                inRange   : {
                    color: [ "#2c3e50", "#3498db", "#ecf0f1", "#e67e22", "#c0392b" ],
                },
                // 中间点（0值）的样式
                splitNumber: 5,
                itemStyle  : {
                    borderWidth: 1,
                },
            },
            series   : [
                {
                    name                : "相关系数",
                    type                : "heatmap",
                    data                : processedData.map(item => [
                        variableNames.indexOf(item.x),
                        variableNames.indexOf(item.y),
                        item.value,
                        item.x,
                        item.y,
                        item.originalValue,
                    ]),
                    label               : {
                        show     : true,
                        formatter: function(params){
                            return params.data[5].toFixed(2)
                        },
                        fontSize : 12,
                    },
                    emphasis            : {
                        itemStyle: {
                            borderColor: "#333",
                            borderWidth: 2,
                        },
                        label    : {
                            fontSize  : 14,
                            fontWeight: "bold",
                        },
                    },
                    progressive         : 1000,
                    progressiveThreshold: 5000,
                },
            ],
        }

        chartInstance.value.setOption(option)

        // 添加窗口大小变化监听
        window.addEventListener("resize", handleResize)
    })
}

// 组件卸载时清理
onUnmounted(() => {
    cleanupChart()
})
</script>

<style scoped>
.result_show {
    display: flex;
    gap: 10px;
    height: 800px;

    .left {
        flex: 1;

        .eChartContainer {
            width: 100%;
            height: 500px;
            padding: 10px 0;
            position: relative;

            .chart {
                width: 100%;
                height: 100%;
                border: 1px solid #eee;
            }
        }
    }

    .right {
        flex: 1;
        display: flex;
        flex-direction: column;
    }
}

/* 相关系数文本样式 */
.strong-correlation {
    color: #c0392b;
    font-weight: bold;
}

.medium-correlation {
    color: #e67e22;
    font-weight: 500;
}

.weak-correlation {
    color: #3498db;
}

.no-correlation {
    color: #7f8c8d;
}

</style>

